package com.example.ch4_04;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            fun();
        }
    }

    public void fun() {
        String basePath = Environment.getExternalStorageDirectory().getPath();
        String filePath = basePath + "/muc/wh+ite.mp3";
        Log.i("wutest", filePath);
        Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();

        mp = new MediaPlayer();
        try {
            mp.setDataSource(filePath);
            mp.prepare();
            mp.start();
            Toast.makeText(this, "正在播放", Toast.LENGTH_LONG).show();
        } catch (IOException e) {

            Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int recode, @NonNull String[] permission, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(recode, permission, grantResults);
        switch (recode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    fun();
                } else {

                    Toast.makeText(this, "没有sd卡读写权限", Toast.LENGTH_LONG).show();
                    finish();
                }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mp.stop();
        mp = null;
    }
}